package net.ncraft.mc.ezframework.core.handler.configuration;

import net.ncraft.mc.ezframework.core.SpigotEzFrameworkCore;
import net.ncraft.mc.ezframework.core.annotations.config.EConfiguration;
import net.ncraft.mc.ezframework.core.annotations.config.EConfigurations;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import org.reflections.Reflections;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

public class ConfigurationHandler {


    private static final List<Class> CONFIGURATION_CLASSES = new ArrayList<>();

    public static void load(JavaPlugin plugin) {
        Reflections r = new Reflections(plugin.getClass().getPackageName());
        CONFIGURATION_CLASSES.addAll(r.getTypesAnnotatedWith(EConfigurations.class));
        registerConfiguration();
    }

    private static void registerConfiguration() {
        for (Class configurationClass : CONFIGURATION_CLASSES) {

            EConfigurations classAnn = (EConfigurations) configurationClass.getAnnotation(EConfigurations.class);
            String path = classAnn.path();

            Field[] configs = configurationClass.getDeclaredFields();

            for (Field config : configs) {
                if (!config.isAnnotationPresent(EConfiguration.class)) continue;
                EConfiguration configAnn = config.getAnnotation(EConfiguration.class);
                String configName = configAnn.name();

                File dir = new File(SpigotEzFrameworkCore.getPlugin().getDataFolder(), path);
                File configFile = new File(dir, configName);

                if (!dir.exists()) {
                    dir.mkdirs();
                }

                if (!configFile.exists()) {
                    try (InputStream resource = SpigotEzFrameworkCore.getPlugin().getResource(configName)) {
                        Files.copy(resource, new File(dir, configName).toPath());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

                FileConfiguration configuration = new YamlConfiguration();
                try {
                    configuration.load(new File(dir, configName));
                    ConfigurationCenter.addConfiguration(configName, configuration);
                } catch (IOException | InvalidConfigurationException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
